//当前页面移动完毕
var endCurrPage = false;
//后续页面移动完毕
var endNextPage = false;
//入场动画和出场动画
var outClass = '';
var inClass = '';

var animEndEventNames = {
        'WebkitAnimation': 'webkitAnimationEnd',
        'OAnimation': 'oAnimationEnd',
        'msAnimation': 'MSAnimationEnd',
        'animation': 'animationend'
    },
    // animation end event name
    animEndEventName = animEndEventNames[Modernizr.prefixed('animation')]

$(function() {
    //保存各个View的默认class
    $(".pt-page").each(function() {
        var $page = $(this);
        $page.data('originalClassList', $page.attr('class'));
    });
    //设置默认页面
    $(".pt-page").eq(0).addClass('pt-page-current');

    //添加动画样式单选框
    var str = "";
    for (var i = 1; i <= 67; i++) {
        str += '<input type="radio" name="myAnimation" value="' + i + '" />效果' + i;
        if (i % 7 == 0) {
            str += "<br/>";
        }
    }
    $("#radiosDiv").html(str);
});

//View切换
function changeView(newView) {
    //设置动画效果
    var animationType = $('input:radio[name="myAnimation"]:checked:eq(0)').val();

    outClass = 'pt-page-moveToBottom pt-page-ontop';
    inClass = 'pt-page-scaleUp';

    $currPage = $(".pt-page-current").eq(0);
    $nextPage = $(newView);

    //清除原来添加的动画，层级等样式(正常动画结束时会自动清除，这样做防止用户在动画结束前就点击切换其他的)
    $(".pt-page").each(function() {
        $(this).attr('class', $(this).data('originalClassList'));
    });
    $currPage.addClass("pt-page-current");
    $nextPage.addClass("pt-page-current");


    //如果就是当页则不切换
    if ($currPage.attr("id") == $nextPage.attr("id")) {
        console.log("不切换");
        return;
    }

    //新页面入场
    $currPage.addClass(outClass).on(animEndEventName, function() {
        $currPage.off(animEndEventName);

        endCurrPage = true;
        console.log("endNextPage::", endNextPage);
        if (endNextPage) {
            onEndAnimation($currPage, $nextPage);
        }
    });

    //旧页面出场
    $nextPage.addClass(inClass).on(animEndEventName, function() {
        $nextPage.off(animEndEventName);
        endNextPage = true;
        console.log("endCurrPage::", endCurrPage);
        console.log("currPage::", $currPage);
        console.log("nextPage::", $nextPage);
        if (endCurrPage) {
            onEndAnimation($currPage, $nextPage);
        }
    });
}

//所有动画都结束后
function onEndAnimation($outpage, $inpage) {
    endCurrPage = false;
    endNextPage = false;
    //resetPage( $outpage, $inpage );
    //isAnimating = false;
    $outpage.attr('class', $outpage.data('originalClassList'));
    $inpage.attr('class', $inpage.data('originalClassList') + ' pt-page-current');
}
